// ==UserScript==
// @name			html5 desktop notification
// @namespace		com.jhdxr.userscript
// @description		implement the desktop notification in firefox.
// @include			http://*
// @include			https://*
// @include			file:///*
// @run-at			document-idle
// @copyright		jhdxr
// @version			0.1
// ==/UserScript==


(function(){
	const PERMISSION_ALLOWED = 0; //indicates that the user has granted permission to scripts with this origin to show notifications.
	const PERMISSION_NOT_ALLOWED = 1; //indicates that the user has not taken an action regarding notifications for scripts from this origin.
	const PERMISSION_DENIED = 2; //indicates that the user has explicitly blocked scripts with this origin from showing notifications.
	
	if(unsafeWindow.webkitNotifications != undefined){
		GM_log('webkitNotifications is already supported!');
		return;
	}
	if(!GM_notification){
		alert('you need the latest scriptish to run this script!');
		return;
	}
	
	var permission = function(){
	}
	permission.get = function(domain){
		return GM_getValue('domain_' + domain, PERMISSION_NOT_ALLOWED);
	}
	permission.set = function(domain, value){
		if(value != PERMISSION_NOT_ALLOWED){
			GM_setValue('domain_' + domain, value);
		}else{
			GM_deleteValue('domain_' + domain);
		}
	}
	
	var notification = function(icon = null, title = '', content = ''){
		this.ondisplay = function(){};
		this.onerror = function(){};
		this.onclose = function(){}; //todo
		this.onclick = function(){};
		
		//this.replaceId = GM_generateUUID();
		this.show = function(){
			try{
				GM_notification(content, title, icon, function() {this.onclick(); });
				this.ondisplay();
			}catch(e){
				this.onerror();
			}
		}
	}
	
	unsafeWindow.webkitNotifications = new function(){
		var _domain = '';
		var _permission = false;
		this.checkPermission = function(){
			return _permission;
		}
		this.requestPermission = function() {
			GM_log(_domain + ':permission requested');
			if(_permission == PERMISSION_NOT_ALLOWED){
				if(confirm('The website ' + _domain + ' is asking for permission to show desktop notifications. Do you want to allow the website ?')){
					permission.set(_domain, PERMISSION_ALLOWED);
					_permission = PERMISSION_ALLOWED;
				}else{
				//	permission.set(_domain, PERMISSION_DENIED);
					_permission = PERMISSION_DENIED;
				}
			}
		}
		this.createNotification = function(icon, title, content){
			if(_permission == PERMISSION_NOT_ALLOWED){
				this.requestPermission();
			}else if(_permission == PERMISSION_DENIED){
				GM_log(_domain + ':permission denied');
				return false;
			}
			var n = new notification(icon, title, content);
			return n;
		}
		this.createHTMLNotification = function(html){
			throw new Exception('unsupported method');
		}
		
		_domain = window.location.host;
		_permission = permission.get(_domain);
	}
})();
